package com.tim.bos;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EntityUtils {
	
	public static boolean isValid(BaseEntity entity, boolean includeNull) {
		if (entity == null) {
			return false;
		}
		if (entity.getObjectstatus() == null) {
			return includeNull ? entity.getObjectstatus() == null : entity
					.getObjectstatus() != null;
		} else {
			return EntityStatus.VALID == entity.getObjectstatus();
		}
	}

	/**
	 * 将一个 JavaBean 对象转化为一个 Map
	 * 
	 * @param bean
	 *            要转化的JavaBean 对象
	 * @return 转化出来的 Map 对象
	 * @throws java.lang.reflect.InvocationTargetException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */

	public static Map<String, Object> convertToMap(ICoreObject bean,
			String... excludePropertyNames) {
		Class type = bean.getClass();
		Map returnMap = new HashMap<String, Object>();
		BeanInfo beanInfo;
		try {
			beanInfo = Introspector.getBeanInfo(type);
		} catch (IntrospectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new HashMap<String, Object>();
		}

		List<String> exlist = Arrays.asList(excludePropertyNames);
		PropertyDescriptor[] propertyDescriptors = beanInfo
				.getPropertyDescriptors();
		for (int i = 0; i < propertyDescriptors.length; i++) {
			PropertyDescriptor descriptor = propertyDescriptors[i];
			String propertyName = descriptor.getName();
			if (!propertyName.equals("class") && !exlist.contains(propertyName)) {
				Method readMethod = descriptor.getReadMethod();

				Object result;
				try {
					result = readMethod.invoke(bean, new Object[0]);

					if (result != null) {
						returnMap.put(propertyName, result);
					} else {
						returnMap.put(propertyName, "");
					}
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return returnMap;
	}
}
